package com.maidou.qiantai.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.maidou.qiantai.common.utils.util.WebUtils;
import com.maidou.qiantai.domain.*;
import com.maidou.qiantai.dto.order.OrderAddDto;
import com.maidou.qiantai.vo.member.CartVo;
import com.maidou.qiantai.vo.member.MemberVo;
import com.maidou.qiantai.vo.order.OrderItemVo;
import com.maidou.qiantai.vo.order.OrderStatusVo;
import com.maidou.qiantai.vo.order.OsOrderItemInfoVo;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.maidou.qiantai.mapper.OsOrderMapper;
import com.maidou.qiantai.service.IOsOrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 订单Service业务层处理
 * 
 * @author maidou
 * @date 2024-03-15
 */
@Service
public class OsOrderServiceImpl implements IOsOrderService 
{
    @Resource
    private OsOrderMapper osOrderMapper;

    @Resource
    private MemberAddressServiceImpl memberAddressService;

    @Resource
    private CartServiceImpl cartService;

    @Resource
    private OsOrderItemServiceImpl orderItemService;

    @Resource
    private MemberServiceImpl memberService;

    @Resource
    private OsOrderOperateHistoryServiceImpl osOrderOperateHistoryService;

    @Resource
    private SpuServiceImpl spuService;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OsOrder selectOsOrderById(Long id)
    {
        return osOrderMapper.selectOsOrderById(id);
    }

    /**
     * 查询订单列表
     * 
     * @param osOrder 订单
     * @return 订单
     */
    @Override
    public List<OsOrder> selectOsOrderList(OsOrder osOrder)
    {
        return osOrderMapper.selectOsOrderList(osOrder);
    }

    /**
     * 新增订单
     * 
     * @param osOrder 订单
     * @return 结果
     */
    @Override
    public int insertOsOrder(OsOrder osOrder)
    {
        osOrder.setCreateTime(DateUtils.getNowDate());
        return osOrderMapper.insertOsOrder(osOrder);
    }

    /**
     * 修改订单
     * 
     * @param osOrder 订单
     * @return 结果
     */
    @Override
    public int updateOsOrder(OsOrder osOrder)
    {
        osOrder.setUpdateTime(DateUtils.getNowDate());
        return osOrderMapper.updateOsOrder(osOrder);
    }

    /**
     * 批量删除订单
     * 
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOsOrderByIds(Long[] ids)
    {
        return osOrderMapper.deleteOsOrderByIds(ids);
    }

    /**
     * 删除订单信息
     * 
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOsOrderById(Long id)
    {
        Integer a = orderItemService.deleteOsOrderItemByOrderId(id);
        Integer b = osOrderOperateHistoryService.deleteOsOrderOperateHistoryByOrderId(id);
        return osOrderMapper.deleteOsOrderById(id);
    }

    /**
     * 订单创建
     * @param orderAddDto
     * @return
     */
    @Override
    @Transactional
    public OsOrder insertOsOrderAdd(OrderAddDto orderAddDto) throws ParseException {
        OsOrder osOrder = new OsOrder();
        //用户信息
        Long id = WebUtils.getMemberIdByAccessToken();
        osOrder.setMemberId(id);
        MemberVo memberVo = memberService.selectUserinfoById(id);
        osOrder.setMemberUsername(memberVo.getUsername());
        //地址信息
        Long addressId = orderAddDto.getAddressId();
        MemberAddress memberAddress = memberAddressService.selectMemberAddressById(addressId);
        osOrder = addressAndOrder(memberAddress, osOrder);
        //生成订单基本信息 生成订单项信息
        List<Long> cartIds = orderAddDto.getCartIds();
        osOrder = createOrder(osOrder,cartIds);
        //生成订单状态信息
        OsOrderOperateHistory osOrderOperateHistory = new OsOrderOperateHistory();
        osOrderOperateHistory.setOrderId(osOrder.getId());
        osOrderOperateHistory.setOperateMan("用户");
        osOrderOperateHistory.setOrderStatus(0l);
        osOrderOperateHistory.setIsDelete(0);
        osOrderOperateHistoryService.insertOsOrderOperateHistory(osOrderOperateHistory);
        //删除购物车选中信息
        String s = JSON.toJSONString(cartIds);
        Long[] longs = JSONObject.parseObject(s, Long[].class);
        cartService.deleteCartByIds(longs);

        return osOrder;
    }

    /**
     * 查询订单信息
     * @param payStatus
     * @return
     */
    @Override
    public List<OrderStatusVo> selectOsOrderVoList(Integer payStatus) {
        Long memberId = WebUtils.getMemberIdByAccessToken();
        if (payStatus==-1){
            payStatus=null;
        }
        List<OsOrder> list= osOrderMapper.selectOsOrderByMemberIdAndByStatus(memberId,payStatus);
        List<OrderStatusVo> collect = list.stream().map(item -> {
            OrderStatusVo orderStatusVo = new OrderStatusVo();
            BeanUtils.copyProperties(item, orderStatusVo);
            Long id = item.getId();
            List<OsOrderItem> orderItems = orderItemService.selectOsOrderItemByIds(id);
            orderStatusVo.setOrderItemVos(orderItems);
            return orderStatusVo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public OrderStatusVo selectOsOrderItemInfo(Long id) {
        OsOrder order = osOrderMapper.selectOsOrderById(id);
        OrderStatusVo orderStatusVo = new OrderStatusVo();
        BeanUtils.copyProperties(order,orderStatusVo);
        Long id1 = order.getId();
        List<OsOrderItem> orderItems = orderItemService.selectOsOrderItemByIds(id1);
        orderStatusVo.setOrderItemVos(orderItems);
        return orderStatusVo;
    }

    @Override
    public Integer updateOsOrderByOrderId(Long id) {
        Object type = WebUtils.getRequestParameter("type");
        Long aLong = JSONObject.parseObject(JSON.toJSONString(type), Long.class);
        OsOrder osOrder = new OsOrder();
        osOrder.setId(id);
        osOrder.setStatus(aLong);
        osOrder.setPayType(1l);
        osOrderMapper.updateOsOrder(osOrder);
        //添加积分
        if(aLong>2&&aLong<5){
            OsOrder osOrder1 = osOrderMapper.selectOsOrderById(id);
            Long memberIdByAccessToken = WebUtils.getMemberIdByAccessToken();
            Member member = memberService.selectMemberById(memberIdByAccessToken);
            member.setGrowth(member.getGrowth()+osOrder1.getGrowth());
            member.setIntegration(member.getIntegration()+osOrder1.getIntegration());
            memberService.updateMember(member);
            //添加商品销量
            List<Long> spuIdList = orderItemService.selectSpuIdByOrderId(id);
            spuIdList.forEach(spuId->{
                Spu spu = spuService.selectSpuById(spuId);
                spu.setNum(spu.getNum()+1);
                spuService.updateSpu(spu);
            });
        }
        //修改状态
        OsOrderOperateHistory osOrderOperateHistory = new OsOrderOperateHistory();
        osOrderOperateHistory.setOrderId(id);
        osOrderOperateHistory.setOrderStatus(aLong);
        return osOrderOperateHistoryService.updateOsOrderOperateHistoryByOrderId(osOrderOperateHistory);
    }

    /**
     * 封装地址信息到订单信息
     * @param memberAddress
     * @param osOrder
     * @return
     */
    public OsOrder addressAndOrder(MemberAddress memberAddress,OsOrder osOrder) {
        osOrder.setReceiverName(memberAddress.getName());
        osOrder.setReceiverPhone(memberAddress.getPhone());
        osOrder.setReceiverPostCode(memberAddress.getPostCode());
        osOrder.setReceiverProvince(memberAddress.getProvince());
        osOrder.setReceiverCity(memberAddress.getCity());
        osOrder.setReceiverRegion(memberAddress.getRegion());
        osOrder.setReceiverDetailAddress(memberAddress.getDetailAddress());
        return osOrder;
    }
    /**
     * 封装订单信息
     * @param osOrder
     * @return
     */
    public OsOrder createOrder(OsOrder osOrder,List<Long> cartIds) throws ParseException {

        String uuid = UUID.randomUUID().toString();
        osOrder.setOrderSn(uuid);//订单号
        List<CartVo> list= cartService.selectCartVoBatchListById(cartIds);
        //金额计算
        BigDecimal amount = new BigDecimal(0);
        for (CartVo cart:list
             ) {
            BigDecimal num = BigDecimal.valueOf(cart.getNum());
            BigDecimal multiply = num.multiply(cart.getSkuInfoVo().getPrice());
            amount = amount.add(multiply);
        }
        osOrder.setTotalAmount(amount);
        //应付金额
        osOrder.setPayAmount(amount);
        osOrder.setFreightAmount(new BigDecimal(0));
        osOrder.setPromotionAmount(new BigDecimal(0));
        osOrder.setIntegrationAmount(new BigDecimal(0));
        osOrder.setCouponAmount(new BigDecimal(0));
        osOrder.setDiscountAmount(new BigDecimal(0));
        osOrder.setPayType(0l);
        osOrder.setSourceType(0l);
        osOrder.setStatus(0l);
        osOrder.setIntegration(5l);
        osOrder.setGrowth(50l);
        osOrder.setBillType(1l);
        osOrder.setConfirmStatus(0l);
        osOrder.setDeleteStatus(0l);
        osOrder.setUseIntegration(0l);
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        // 将当前日期加上两天
        calendar.add(Calendar.DAY_OF_MONTH, 2);
        // 输出添加两天后的日期
        Date time = calendar.getTime();
        osOrder.setDeliveryTime(time );
        osOrder.setIsDelete(0);
        int i = osOrderMapper.insertOsOrder(osOrder);
        if (i==0){
            return null;
        }

        for (CartVo cart:
                list) {
            OsOrderItem osOrderItem = new OsOrderItem();
            osOrderItem.setOrderId(osOrder.getId());
            osOrderItem.setOrderSn(osOrder.getOrderSn());
            osOrderItem.setGiftGrowth(osOrder.getGrowth());
            osOrderItem.setGiftIntegration(osOrder.getIntegration());
            osOrderItem.setRealAmount(new BigDecimal(0));
            osOrderItem.setIntegrationAmount(new BigDecimal(0));
            osOrderItem.setCouponAmount(new BigDecimal(0));
            osOrderItem.setPromotionAmount(new BigDecimal(0));
            osOrderItem.setIsDelete(0);
            osOrderItem.setSkuQuantity(Long.valueOf(cart.getNum()));
            osOrderItem.setSkuAttrsVals(cart.getSkuInfoVo().getSkuDesc());
            osOrderItem.setSkuPrice(cart.getSkuInfoVo().getPrice());
            osOrderItem.setSkuPic(cart.getSkuInfoVo().getSkuDefaultImg());
            osOrderItem.setSkuName(cart.getSkuInfoVo().getSkuName());
            osOrderItem.setSkuId(cart.getSkuInfoVo().getId());
            osOrderItem.setCategoryId(0l);
            osOrderItem.setSpuId(cart.getSpuRecommendVo().getId());
            osOrderItem.setSpuName(cart.getSpuRecommendVo().getSpuName());
            osOrderItem.setSpuPic(cart.getSpuRecommendVo().getHeader());
            orderItemService.insertOsOrderItem(osOrderItem);
        }
        return osOrder;
    }



}
